package com.example.weathersuggestion;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.text.InputType;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.scrollview.CenterLockHorizontalScrollview;
import com.example.scrollview.CustomListAdapter;
import com.slidingmenu.lib.SlidingMenu;
public class MainActivity extends Activity {
	private String displayState = "NC", displayZip="28223";
	CurrentConditions cc;
	Context c;
	boolean useGPS = false;
	
	
	
	String[] menuItems = {"Use Current Location","Use Home Location", "Set Home Location"};//https://github.com/jfeinstein10/SlidingMenu
	
	private CenterLockHorizontalScrollview clothingScrollview = null;
	private CustomListAdapter customClothingListAdapter = null;
	private CenterLockHorizontalScrollview activityScrollview = null;
	private CustomListAdapter customActivityListAdapter = null;;
	
	//private LocationManager locationManager = null;
	//private LocationProvider provider = null;
	//private LocationListener locListener = null;
	//private Double[] currLocation = new Double[2];
	
	private LocationList locationListener;
	
	private Double currentTemp = null;
	private Double precipValue = null;
	

	
	private ArrayList<String> clothingList = new ArrayList<String>();;
	
	private ArrayList<String> activityList = new ArrayList<String>();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		c= this;
		setContentView(R.layout.activity_main);
		locationListener = new LocationList(this);
//		Log.e("location", " "+ locationListener.getGPSZip());
//		useGPS = true;
		setupLoc();
		setupSlidingMenu();
		if(useGPS){
			
		}
		else{
			displayZip = locationListener.getHome();
		}

		//TOO EARLY setupScrollViews();
		//locationListener = new LocationList(getBaseContext()); 
		new Connection().execute();//TODO Put this somewhere better
		
		//Not sure if need to put in onCreate() as well as onStart() -RB

		
	}
	
	@Override
	protected void onStart() {
	    super.onStart();

	}

	private void enableLocationSettings() {
	    Intent settingsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
	    startActivity(settingsIntent);
	}

	private void setupSlidingMenu() {
		final SlidingMenu sMenu = new SlidingMenu(this);
		
		sMenu.setMode(SlidingMenu.LEFT);
		sMenu.setBehindOffsetRes(R.dimen.behindOff);
		sMenu.setFadeDegree(0.35f);
		sMenu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
		sMenu.setMenu(R.layout.slide_menu);
		sMenu.setShadowWidth(R.dimen.shadowWidth);
		sMenu.setShadowDrawable(R.drawable.shadow);
		sMenu.setShadowWidthRes(R.dimen.shadowWidth);
		sMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);

		ListView lv = (ListView) findViewById(R.id.slideMenuListView); 
		 lv.setAdapter(new ArrayAdapter<String>(this,
	        		android.R.layout.simple_list_item_1, menuItems));

		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				switch (arg2)
				{
				case 0://Refresh
					useGPS = true;
					new Connection().execute();
					sMenu.toggle();
					break;
				case 1: //Change Location
//					intent = new Intent(getBaseContext(), LocationActivity.class);
//					startActivity(intent);
					useGPS = false;
					displayZip = locationListener.getHome();
					new Connection().execute();
					sMenu.toggle();
					break;
				case 2:
					//EditText input = new EditText(getBaseContext());
					AlertDialog.Builder alert = new AlertDialog.Builder(c);
					final EditText in = new EditText(c);
					in.setInputType(InputType.TYPE_CLASS_NUMBER);
					alert.setView(in);
					 alert.setTitle("Input a 5 digit ZIP Code");
					 alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
				            public void onClick(DialogInterface dialog, int whichButton) {
				            	String temp = in.getText().toString();
				            	if (temp.trim().length() != 5){
				            		Toast.makeText(c, "That wasn't 5 digits...", Toast.LENGTH_SHORT).show();
				            	}
				            	else{
				            		locationListener.setHome(temp);
				            		Log.e("home", locationListener.getHome());
				            	}
				                         
				            } // End of onClick(DialogInterface dialog, int whichButton)
				        }); //End of alert.setPositiveButton
				            alert.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
				              public void onClick(DialogInterface dialog, int whichButton) {
				                // Canceled.
				                  dialog.cancel();
				              }
				        }); //End of alert.setNegativeButton
				            AlertDialog alertDialog = alert.create();
				            alertDialog.show();
					
					break;
					
				}
				
			}
		});	
	}
	
	private void setupScrollViews(){
		String[] tempStrings = null;
		ActivitySuggestion actSuggestion = new ActivitySuggestion();
		ClothingSuggestion cloSuggestion = new ClothingSuggestion();
		
		clothingList = cloSuggestion.getSuggestion(currentTemp, precipValue);
		activityList = actSuggestion.getSuggestion(currentTemp, precipValue);
		
		if(clothingList.size()==1);
		{
			tempStrings = clothingList.get(0).split(",");
			clothingList = new ArrayList<String>();
			
			for(String s: tempStrings){
				clothingList.add(s);
			}
		}
		
		clothingScrollview = (CenterLockHorizontalScrollview) findViewById(R.id.clothingScrollView);
		customClothingListAdapter = new CustomListAdapter(this,
				R.layout.sugg_list_item, clothingList);
		clothingScrollview.setAdapter(this, customClothingListAdapter);

		activityScrollview = (CenterLockHorizontalScrollview) findViewById(R.id.activityScrollView);
		customActivityListAdapter = new CustomListAdapter(this,
				R.layout.sugg_list_item, activityList);
		activityScrollview.setAdapter(this, customActivityListAdapter);
	}


	private void setupLoc(){

	    // This verification should be done during onStart() because the system calls
	    // this method when the user returns to the activity, which ensures the desired
	    // location provider is enabled each time the activity resumes from the stopped state.
	    //LocationManager locationManager =
	     //       (LocationManager) getSystemService(Context.LOCATION_SERVICE);
	    //final boolean gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
	    
	    //Create locationList object that handles location listening -RB
	    locationListener = new LocationList(c);
	    //boolean gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
	    
	    if (!locationListener.isGPSProviderEnabled()) {
	    	// Build an alert dialog here that requests that the user enable
	    	// the location services, then when the user clicks the "OK" button,
	    	// call enableLocationSettings()
	    	AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
	    	alertDialogBuilder
	    	.setTitle("GPS not Enabled")
	    	.setMessage("GPS must be enabled to determine you're current location. Do you want to enable GPS?")
	    	.setCancelable(true)
	    	.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

	    		@Override
	    		public void onClick(DialogInterface dialog, int which) {
	    			enableLocationSettings();

	    		}
	    	})
	    	.setNegativeButton("No", new DialogInterface.OnClickListener() {

	    		@Override
	    		public void onClick(DialogInterface dialog, int which) {
	    			dialog.cancel();	
	    		}
	    	});

	    	AlertDialog alertDialog = alertDialogBuilder.create();
	    	alertDialog.show();

	    }
	     
	    //Not sure if this is best place to put. Need to somehow update the state/zip when user changes selected 

	    
	//    displayState = locationListener.getStateSelectedLocation();
	   
	    try{
	    displayZip = locationListener.getGPSZip();
	    }catch (Exception e){
	    	
	    }
	    finally{}
	    if (displayZip == null){
	    	Toast.makeText(getBaseContext(), "Out of range, using home location", Toast.LENGTH_SHORT).show();
	    	displayZip = locationListener.getHome();
	    }
	}
	
	private class Connection extends AsyncTask<String, String, String>{
		
		HttpClient client = new DefaultHttpClient();
		//ProgressDialog bar;
		
		HttpPost postRequest = new HttpPost("http://api.wunderground.com/api/ae8956ff5c12efa3/conditions/q/"+displayZip+".json");//TODO make this based on GPS/Stored Location
	protected void onPreExecute(){
		if (useGPS) setupLoc();
		
	}	
		@Override
			protected String doInBackground(String... arg0) {
			try {
				HttpResponse response = client.execute(postRequest);
				InputStream in;
				in = response.getEntity().getContent();
				cc = new CurrentConditions(in);
			} catch (ClientProtocolException e) {
				
				e.printStackTrace();
			} catch (IOException e) {
				
				e.printStackTrace();
			}
			return null;
		}
		protected void onPostExecute(String para){
			if (cc.isValid()){
			TextView temp =  (TextView) findViewById(R.id.tempTextView);
			TextView feels = (TextView) findViewById(R.id.feelsLikeText);
			TextView updatedTime = (TextView) findViewById(R.id.lastUpdatedTextView);
			updatedTime.setText(cc.getObservationTime() + "\n" + cc.getObvsLocation());
			temp.setText(cc.getTemp() + "\u00B0F");
			feels.setText("Feels Like " + cc.getFeelsLikeTemp() +"\u00B0F");
			ImageView wIcon = (ImageView) findViewById(R.id.homeWeatherIcon);
			wIcon.setImageResource(setImageIcon(cc.getCondition()));
			
			currentTemp = cc.getTemp();
			precipValue = cc.getprecipChance();
			if (precipValue == 0.00){
				precipValue = 10.00;
			}
			else{
				precipValue = 60.00;
			}
			
			
			setupScrollViews();}
			else Toast.makeText(c, "Not a valid zip code", Toast.LENGTH_SHORT).show();
		}
		
	}
	
	public int setImageIcon(int icon){
		int res;
		switch (icon){
		case CurrentConditions.CLEAR:
			res = R.drawable.clear;
			break;
		case CurrentConditions.RAIN:
			res = R.drawable.rain;
			break;
		case CurrentConditions.SNOW:
			res = R.drawable.snow;
			break;
		case CurrentConditions.TSTORMS:
			res = R.drawable.tstorms;
			break;
		case CurrentConditions.HAZY:
			res = R.drawable.hazy;
			break;
		case CurrentConditions.CLOUDY:
			res = R.drawable.cloudy;
			break;
		case CurrentConditions.PARTLY_CLOUDY:
		case CurrentConditions.MOSTLY_CLOUDY:
			res = R.drawable.partlycloudy;
			break;
		default:
				res = R.drawable.clear;
				
		}
		
		return res;
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}
